package com.beiing.tianshuai.tianshuai.huodong;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.text.TextUtils;
import android.view.View;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.beiing.tianshuai.tianshuai.R;
import com.beiing.tianshuai.tianshuai.activity.NewDiscoveryPublishActivity;
import com.beiing.tianshuai.tianshuai.base.BaseActivity;
import com.beiing.tianshuai.tianshuai.entity.CodeBean;
import com.beiing.tianshuai.tianshuai.entity.EventTypesBean;
import com.beiing.tianshuai.tianshuai.entity.UploadActiveImgBean;
import com.beiing.tianshuai.tianshuai.entity.UserInfoBean;
import com.beiing.tianshuai.tianshuai.huodong.presenter.HuoDongPublishPresenter;
import com.beiing.tianshuai.tianshuai.huodong.view.IHuoDongPublishView;
import com.beiing.tianshuai.tianshuai.util.DateUtil;
import com.beiing.tianshuai.tianshuai.util.LogUtils;
import com.beiing.tianshuai.tianshuai.widget.GlideImageLoader;
import com.bigkoo.pickerview.builder.OptionsPickerBuilder;
import com.bigkoo.pickerview.builder.TimePickerBuilder;
import com.bigkoo.pickerview.listener.OnOptionsSelectListener;
import com.bigkoo.pickerview.listener.OnTimeSelectListener;
import com.bigkoo.pickerview.view.OptionsPickerView;
import com.bigkoo.pickerview.view.TimePickerView;
import com.bumptech.glide.Glide;
import com.google.gson.Gson;
import com.tianshuai.gallerypic.config.GalleryConfig;
import com.tianshuai.gallerypic.config.GalleryPick;
import com.tianshuai.gallerypic.inter.IHandlerCallBack;
import com.zxy.tiny.Tiny;
import com.zxy.tiny.callback.FileCallback;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import butterknife.BindView;
import okhttp3.ResponseBody;

/**
 * Created by magikliu on 2017/10/20.
 */

public class HuoDongPublishActivity extends BaseActivity implements IHuoDongPublishView{

    private static final String TAG = "HuoDongPublishActivity";
    private OptionsPickerView huoDongTypePicker, bookingWayPicker;
    private List<String> huoDongTypeList = new ArrayList<>();
    private List<String> mImagePath = new ArrayList<>();
    private List<File> mImageFiles = new ArrayList<>();
    private String mPhotoPath;
    private HuoDongPublishPresenter mPresenter;
    private List<Integer> tids = new ArrayList<>();
    private String contact;             //活动联系人
    private String create_time;         //活动创建时间
    private String[] bookingWays = {"否", "需要"};

    private int tid;        //活动类型id
    private int uid;        //用户id
    private String cover;   //活动封面图
    private String title;   //活动标题
    private String content; //活动内容
    private int is_three = 0;       //是否需要第三方购票地址  0-本站  1-第三方
    private String three_url;       //第三方购票地址

    private boolean isSelected;

    @BindView(R.id.toolbar_iv_back)
    ImageView toolbarIvBack;
    @BindView(R.id.toolbar_tv_title)
    TextView toolbarTvTitle;
    @BindView(R.id.toolbar_tv_publish)
    TextView toolbarTvReview;      //预览
    @BindView(R.id.rv_huodong_type)
    RelativeLayout rvHuodongType;
    @BindView(R.id.tv_huodong_type)
    TextView tvHuodongType;
    @BindView(R.id.et_huodong_price)
    EditText etHuodongPrice;    //报名费用
    @BindView(R.id.et_ticket_num)
    EditText etTicketNum;       //票数
    @BindView(R.id.rv_begin_time)
    RelativeLayout beginTime;       //活动开始时间
    @BindView(R.id.tv_begin_time)
    TextView tvBeginTime;
    @BindView(R.id.rv_end_time)
    RelativeLayout endTime;         //活动结束时间
    @BindView(R.id.tv_end_time)
    TextView tvEndTime;
    @BindView(R.id.et_huodong_site)
    EditText huodongSite;           //活动举办地点
    @BindView(R.id.et_huodong_sponsor)
    EditText huodongSponsor;        //活动主办方
    @BindView(R.id.et_sponsor_tel)
    EditText sponsorTel;            //主办方联系方式
    @BindView(R.id.tv_huodong_way)
    TextView tvBookingWay;
    @BindView(R.id.rv_booking_url)
    RelativeLayout rvBookingUrl;
    @BindView(R.id.et_booking_url)
    EditText etBookingUrl;
    @BindView(R.id.iv_select)
    ImageView ivSelect;     //勾选同意用户协议

    @BindView(R.id.tv_active_title)
    TextView activeTitle;
    @BindView(R.id.tv_upload_cover)
    TextView uploadCover;
    @BindView(R.id.framelayout)
    FrameLayout frameLayout;
    @BindView(R.id.iv_cover)
    ImageView ivCover;
    @BindView(R.id.tv_publish)
    TextView tvPublish;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_huodong_publish;
    }

    @Override
    protected void init() {
        initData();
        initPresenter();
        initHuoDongTypePicker();
        initBookingWayPicker();
        initListener();
    }

    private void initData() {
        Intent intent = this.getIntent();
        title = intent.getStringExtra("title");
        content = intent.getStringExtra("content");
        activeTitle.setText(title);
        uid = Integer.parseInt(UserInfoBean.getUid(mContext));
        contact = UserInfoBean.getNickName(mContext);
        create_time = System.currentTimeMillis() / 1000 + "";

        WindowManager wm = (WindowManager)this.getSystemService(Context.WINDOW_SERVICE);
        int width = 0;
        if (wm != null) {
            width = wm.getDefaultDisplay().getWidth();
            float height = (float)width / (16f/9f);
            LinearLayout.LayoutParams layoutParams = (LinearLayout.LayoutParams) frameLayout.getLayoutParams();
            layoutParams.height = (int)height;
            frameLayout.setLayoutParams(layoutParams);
        }
    }

    private void initPresenter() {
        mPresenter = new HuoDongPublishPresenter(this);
    }

    private void initHuoDongTypePicker() {
        mPresenter.getHuoDongType();
    }

    private void initBookingWayPicker(){
        bookingWayPicker = new OptionsPickerBuilder(mContext, new OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int options2, int options3, View v) {
                tvBookingWay.setText(bookingWays[options1]);
                if (tvBookingWay.getText().equals("需要")){
                    rvBookingUrl.setVisibility(View.VISIBLE);
                    is_three = 1;
                } else {
                    rvBookingUrl.setVisibility(View.GONE);
                    is_three = 0;
                }
            }
        }).setSubmitText("确定")
                .setCancelText("取消")//取消按钮文字
                .setTitleText("活动类型")
                .setTitleColor(Color.parseColor("#67a0ff"))
                .setSubmitColor(Color.parseColor("#67a0ff"))//确定按钮文字颜色
                .setCancelColor(Color.parseColor("#67a0ff"))//取消按钮文字颜色
                .setSubCalSize(16)//确定和取消文字大小
                .setContentTextSize(18)//滚轮文字大小
                .isDialog(false)//是否显示为对话框样式
                .build();
        bookingWayPicker.setPicker(Arrays.asList("否","需要"));
    }

    private void initListener(){

        toolbarIvBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });

        //预览
        toolbarTvReview.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(mContext, HuoDongPreviewActivity.class);
                intent.putExtra("cover", cover);    //封面图
                intent.putExtra("sponsor", huodongSponsor.getText().toString());  //主办方
                intent.putExtra("title", title);    //活动标题
                intent.putExtra("beginTime", tvBeginTime.getText().toString());      //活动开始时间
                intent.putExtra("endTime", tvEndTime.getText().toString());       //活动结束时间
                intent.putExtra("location", huodongSite.getText().toString());      //活动地点
                intent.putExtra("tel", sponsorTel.getText().toString());           //主办方联系方式
                intent.putExtra("praise", etHuodongPrice.getText().toString());        //活动票价
                intent.putExtra("content1", content);
                if (ableToPublish()){
                    startActivity(intent);
                }
            }
        });

        //上传活动封面图
        uploadCover.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                selectImage();
            }
        });

        //替换图片
        if (ivCover.getVisibility() == View.VISIBLE){
            ivCover.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    selectImage();
                }
            });
        }

        //活动类型选择
        rvHuodongType.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                huoDongTypePicker.show();
            }
        });

        //活动开始时间选择
        beginTime.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                boolean[] type = {true, true, true, true, true, false};
                TimePickerView timePickerView = new TimePickerBuilder(mContext, new OnTimeSelectListener() {
                    @Override
                    public void onTimeSelect(Date date, View v) {
                        tvBeginTime.setText(DateUtil.getFormatTime(date));
                    }
                })
                        .setLabel("  年","月", "日","时","分", null)
                        .setType(type)
                        .setTitleText("开始时间")
                        .setTitleColor(Color.parseColor("#67a0ff"))
                        .setDate(Calendar.getInstance())
                        .setSubmitColor(Color.parseColor("#67a0ff"))//确定按钮文字颜色
                        .setCancelColor(Color.parseColor("#67a0ff"))//取消按钮文字颜色
                        .build();
                timePickerView.show();
            }
        });

        //活动结束时间选择
        endTime.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                boolean[] type = {true, true, true, true, true, false};
                TimePickerView timePickerView = new TimePickerBuilder(mContext, new OnTimeSelectListener() {
                    @Override
                    public void onTimeSelect(Date date, View v) {
                        tvEndTime.setText(DateUtil.getFormatTime(date));
                    }
                })
                        .setLabel("  年","月", "日","时","分", null)
                        .setType(type)
                        .setTitleText("结束时间")
                        .setTitleColor(Color.parseColor("#67a0ff"))
                        .setDate(Calendar.getInstance())
                        .setSubmitColor(Color.parseColor("#67a0ff"))//确定按钮文字颜色
                        .setCancelColor(Color.parseColor("#67a0ff"))//取消按钮文字颜色
                        .build();
                timePickerView.show();
            }
        });

        tvBookingWay.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                bookingWayPicker.show();
            }
        });

        //活动发布
        tvPublish.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                publishActive();
            }
        });

        //勾选同意用户协议
        ivSelect.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (!isSelected){
                    ivSelect.setImageResource(R.mipmap.circle_blue);
                    isSelected = true;
                } else {
                    ivSelect.setImageResource(R.mipmap.login_radio_gray);
                    isSelected = false;
                }
            }
        });
    }

    private void publishActive() {
        if (ableToPublish()) {
            String sponsor = huodongSponsor.getText().toString();
            String huodongBeginTime = DateUtil.date2TimeStamp(tvBeginTime.getText().toString(), "yyyy-MM-dd HH:mm");
            String huodongEndTime = DateUtil.date2TimeStamp(tvEndTime.getText().toString(), "yyyy-MM-dd HH:mm");
            String huodongLocation = huodongSite.getText().toString();
            String sponsortel = sponsorTel.getText().toString();
            float much = TextUtils.isEmpty(etHuodongPrice.getText()) ? 0 : Float.parseFloat(etHuodongPrice.getText().toString());
            int count = TextUtils.isEmpty(etTicketNum.getText()) ? 0 : Integer.parseInt(etTicketNum.getText().toString());

            mPresenter.publishActive(title, tid, uid, sponsor, huodongBeginTime, huodongEndTime, huodongLocation, "", cover, content, contact, sponsortel, much, count, create_time, is_three, three_url);
        }
    }

    private boolean ableToPublish(){
        if (tid == 0){
            showShortText("请选择活动类型");
        } else if (TextUtils.isEmpty(etTicketNum.getText())){
            showShortText("请填写票数");
        } else if (TextUtils.isEmpty(tvBeginTime.getText())){
            showShortText("请填写活动开始时间");
        } else if (TextUtils.isEmpty(tvEndTime.getText())){
            showShortText("请填写活动结束时间");
        } else if (TextUtils.isEmpty(huodongSite.getText())){
            showShortText("请填写举办地点");
        } else if (TextUtils.isEmpty(huodongSponsor.getText())){
            showShortText("请填写主办方");
        } else if (TextUtils.isEmpty(sponsorTel.getText())){
            showShortText("请填写联系方式");
        } else if (is_three == 0){
            three_url = "";
            return true;
        } else {
            if (TextUtils.isEmpty(etBookingUrl.getText().toString())){
                showShortText("请填写第三方购票地址");
            } else {
                three_url = etBookingUrl.getText().toString().trim();
                return true;
            }
        }
        return false;
    }

//    @Override
//    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
//        if (null != data){
//            huodongDetailNew = data.getStringExtra("detail");
//            huodongDetail.setVisibility(View.GONE);
//            webContainer.setVisibility(View.VISIBLE);
//        } else {
//            huodongDetail.setVisibility(View.VISIBLE);
//            webContainer.setVisibility(View.GONE);
//        }
//        if (requestCode == 0){
//            webView.loadDataWithBaseURL(null, huodongDetailNew, "text/html", "utf-8", null);
//        }
//    }

    //图片选择部分
    private void selectImage() {
        List<String> path = new ArrayList<>();
        IHandlerCallBack iHandlerCallBack = new IHandlerCallBack() {
            @Override
            public void onStart() {
            }

            @Override
            public void onSuccess(List<String> photoList) {
                mPhotoPath = photoList.get(0);
                LogUtils.i(mPhotoPath, TAG);
                // 压缩图片
                Tiny.FileCompressOptions tinyOptions = new Tiny.FileCompressOptions();
                Tiny.getInstance().source(mPhotoPath).asFile().withOptions(tinyOptions).compress(new FileCallback() {
                    @Override
                    public void callback(boolean isSuccess, String outfile) {
                        if (isSuccess) {
                            uploadCover.setVisibility(View.GONE);
                            ivCover.setVisibility(View.VISIBLE);
                            File file = new File(outfile);
                            Glide.with(mContext.getApplicationContext())
                                    .load(file)
                                    .into(ivCover);
                            uploadImg(file);
                        } else {
                            ivCover.setVisibility(View.GONE);
                            uploadCover.setVisibility(View.VISIBLE);
                            showShortText("图片过大");
                        }
                    }
                });
            }

            @Override
            public void onCancel() {
            }

            @Override
            public void onFinish() {
            }

            @Override
            public void onError() {
            }
        };
        GalleryConfig galleryConfig = new GalleryConfig.Builder()
                .imageLoader(new GlideImageLoader())                // ImageLoader 加载框架（必填）
                .iHandlerCallBack(iHandlerCallBack)                 // 监听接口（必填）
                .provider("com.beiing.tianshuai.fileprovider")      // provider (必填)
                .pathList(path)                                     // 记录已选的图片
                .multiSelect(false)                             // 是否多选   默认：false
                .crop(true, 16f, 9f, 500, 500)        // 快捷开启裁剪功能，仅当单选 或直接开启相机时有效
                .isShowCamera(true)                                 // 是否现实相机按钮  默认：false
                .filePath("/TianShuai/Pictures")                    // 图片存放路径
                .build();
        GalleryPick.getInstance().setGalleryConfig(galleryConfig).open(HuoDongPublishActivity.this);
    }

    /**
     * 上传图片
     * @param file
     */
    private void uploadImg(File file){
        mPresenter.uploadImg(file);
    }

    @Override
    public void getHuoDongType(EventTypesBean typeBean) {
        for (int i = 0; i < typeBean.getData().getNumber().size(); i++) {
            huoDongTypeList.add(typeBean.getData().getNumber().get(i).getName());
            tids.add(Integer.parseInt(typeBean.getData().getNumber().get(i).getId()));
        }
        huoDongTypePicker = new OptionsPickerBuilder(this, new OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int options2, int options3, View v) {
                String huoDongType = huoDongTypeList.get(options1);
                tvHuodongType.setText(huoDongType);
                tid = tids.get(options1);
            }
        }).setSubmitText("确定")
                .setCancelText("取消")//取消按钮文字
                .setTitleText("活动类型")
                .setTitleColor(Color.parseColor("#67a0ff"))
                .setSubmitColor(Color.parseColor("#67a0ff"))//确定按钮文字颜色
                .setCancelColor(Color.parseColor("#67a0ff"))//取消按钮文字颜色
                .setSubCalSize(16)//确定和取消文字大小
                .setContentTextSize(18)//滚轮文字大小
                .isDialog(false)//是否显示为对话框样式
                .build();
        huoDongTypePicker.setPicker(huoDongTypeList);
    }

    @Override
    public void getUploadResult(ResponseBody responseBody) {
        try {
            String result = responseBody.string();
            LogUtils.i(result, TAG);
            Gson gson = new Gson();
            UploadActiveImgBean uploadActiveImgBean = gson.fromJson(result, UploadActiveImgBean.class);
            cover = uploadActiveImgBean.getData().getCover();
            LogUtils.i(cover, TAG);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void publishActive(CodeBean codeBean) {
        if (codeBean.getCode() == 200){
            showShortText("发布成功");
            NewDiscoveryPublishActivity.newDiscoveryPublishActivity.finish();
            finish();
        }
    }
}
